package cn.itcast.service.impl;

import cn.itcast.constant.MessageConstant;
import cn.itcast.dao.MenuDao;
import cn.itcast.entity.PageResult;
import cn.itcast.entity.QueryPageBean;
import cn.itcast.entity.Result;
import cn.itcast.pojo.Menu;
import cn.itcast.pojo.Permission;
import cn.itcast.pojo.Role;
import cn.itcast.service.MenuService;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenuDao menuDao;


    @Override
    public Result menuPage(QueryPageBean queryPageBean) {
        //开启分页查询
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        //根据条件分页查询检查项信息
        List<Menu> menus = menuDao.menuPage();

        PageInfo<Menu> pageInfo = new PageInfo<>(menus);
        //构建分页数据返回
        PageResult pageResult = new PageResult(pageInfo.getTotal(), menus);
        return new Result(true,"消息返回成功",pageResult);
    }

    @Override
    public Integer handAdd(Menu menu) {
        menuDao.handAdd(menu);
        return menu.getId();
    }

    @Override
    public Result menuPermissions(Integer id) {
        List<Permission> list = menuDao.menuPermissions(id);
        List<Integer> permissionIds = list.stream().map(Permission::getId).collect(Collectors.toList());
        Result result = new Result(true, MessageConstant.QUERY_PERMISSION_SUCCESS, permissionIds);
        return result;
    }

    /**
     * 实现根据id删除菜单
     * @param id
     */
    @Override
    public void deletById(Integer id) {
            menuDao.deletRoleMenu(id);
            menuDao.deletPermissionById(id);
            menuDao.deletmenuById(id);


//        menuDao.deletPermissionById(id);
//        menuDao.deletmenuById(id);
    }

    /**
     * 增加菜单权限
     * @param id
     * @param permissionIds
     */
    @Override
    public void addPremission(Integer id, String permissionIds) {
        String[] permissionIdArr = permissionIds.split(",");
        for (String permissionId : permissionIdArr) {
            Integer PerId  = Integer.parseInt(permissionId);
            menuDao.addPremission(id,PerId);
        }
    }
      /*根据id查询回显*/
    @Override
    public Menu findMenuById(Integer id) {
        Menu menu = menuDao.findMenuById(id);
        return menu;
    }

    @Override
    public void UpdateMenu(Menu menu) {
        menuDao.UpdateMenu(menu);
    }

    @Override
    public void deletPermission(Integer id) {
        try {
            menuDao.deletPermission(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
